const fs = require('fs')
const process = require('process')
const Declaration = require('postcss/lib/declaration.js')
const postcss_scss = require('postcss-scss')

const args = process.argv.splice(2)

var name = args[0]
var _name = name ? ('-' + name) : ''
let customerVariablesPath = 'build_theme/element-variables-customer' + _name + '.scss' // 自定义变量文件路径
let mergedVariablesPath = 'build_theme/element-variables-merged' + _name + '.scss' // 混合后文件路径

let scss = fs.readFileSync(customerVariablesPath, {encoding:'utf-8'})
let root1 = postcss_scss.parse(scss) // 解析为抽象语法树
let nodes = root1.nodes
let customerDeclarationMap = new Map()

nodes.forEach(node => {
  // 判断节点是 变量声明
  if (node instanceof Declaration) {
    /* 
      $--color-primary : #123456 !default;
      ────────┬───────   ────────┬───────
          node.prop          node.value
    */ 
    customerDeclarationMap.set(node.prop, node.value)
  }
})

scss = fs.readFileSync('build_theme/element-variables.scss', {encoding:'utf-8'})
root1 = postcss_scss.parse(scss)
nodes = root1.nodes

nodes.forEach(node => {
  if (node instanceof Declaration) {
    var value = customerDeclarationMap.get(node.prop)
    if(value) {
      node.value = value // 重新赋值
    }
  }
})

fs.writeFileSync(mergedVariablesPath, root1.toString(), {encoding:'utf-8'})
